package com.mk.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mk.exception.BusinessException;
import com.mk.exception.ErrorCode;
import com.mk.exception.ThrowUtils;
import com.mk.manager.CosManager;
import com.mk.manager.upload.FilePictureUpload;
import com.mk.manager.upload.PictureUploadTemplate;
import com.mk.manager.upload.UrlPictureUpload;
import com.mk.mapper.PictureMapper;
import com.mk.model.dto.file.UploadPictureResult;
import com.mk.model.dto.picture.*;
import com.mk.model.entity.Picture;
import com.mk.model.entity.Space;
import com.mk.model.entity.User;
import com.mk.model.enums.PictureReviewStatusEnum;
import com.mk.model.vo.picture.PictureVO;
import com.mk.model.vo.user.UserVO;
import com.mk.service.PictureService;
import com.mk.service.SpaceService;
import com.mk.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author zkm
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2024-12-19 14:42:13
 */
@Slf4j
@Service
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
        implements PictureService {

    @Autowired
    private UserService userService;

    @Autowired
    private CosManager cosManager;
    @Resource
    private FilePictureUpload filePictureUpload;
    @Resource
    private UrlPictureUpload urlPictureUpload;
    @Resource
    private SpaceService spaceService;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Override
    public PictureVO uploadPicture(PictureUploadRequest pictureUploadRequest, Object inputSource, User loginUser) {
        // 1. 参数校验
        Long pictureId = null;
        if (pictureUploadRequest != null) {
            pictureId = pictureUploadRequest.getId();
        }
        Space space = null;
        Long spaceId = pictureUploadRequest.getSpaceId();
        // 如果是更新判断图片是否存在，管理员或创建者才能更新
        if (pictureId != null) {
            Picture oldPicture = this.getById(pictureId);
            ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
            if (!userService.isAdmin(loginUser) && !loginUser.getId().equals(oldPicture.getUserId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }

            // 校验空间是否一致
            if (spaceId == null) {
                spaceId = oldPicture.getSpaceId();
            } else {// 传了 spaceId，必须和原有图片一致
                if (!spaceId.equals(oldPicture.getSpaceId())) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间 id 不一致");
                }
            }
        }

        // 判断空间ID是否存在, 权限校验, 容量校验
        if (spaceId != null && spaceId > 0) {
            space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            // 只有空间创建者才能上传图片
            if (!loginUser.getId().equals(space.getUserId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间权限");
            }
            // 校验额度
            if (space.getTotalSize() >= space.getMaxSize())
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间存储容量不足");
            if (space.getTotalCount() >= space.getMaxCount())
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间存储条数不足");
        }

        // 上传图片，得到图片信息（空间ID不存在上传至公共图库）
        String uploadPathPrefix = String.format("public/%s", loginUser.getId());
        if (space != null) {
            uploadPathPrefix = String.format("space/%s", space.getId());
        }

        PictureUploadTemplate pictureUploadTemplate = filePictureUpload;
        if (inputSource instanceof String) {
            pictureUploadTemplate = urlPictureUpload;
        }
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputSource, uploadPathPrefix);

        // 封装保存图片信息
        Picture picture = buildPicture(loginUser, uploadPictureResult, pictureId);
        // 设置图片名称
        String picName = pictureUploadRequest.getPicName();
        if (StrUtil.isNotBlank(picName)) {
            picture.setName(picName);
        }
        // 设置图片空间ID
        if (space != null) {
            picture.setSpaceId(space.getId());
        }
        // 开启事务
        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
            boolean result = this.saveOrUpdate(picture);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "图片上传失败");
            if (finalSpaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, finalSpaceId)
                        .setSql("totalSize = totalSize + " + picture.getPicSize())
                        .setSql("totalCount = totalCount + 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return picture;
        });
        return PictureVO.objToVo(picture);
    }

    @Override
    public void deletePicture(Long id, User loginUser) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 判断图片是否存在
        Picture picture = this.getById(id);
        ThrowUtils.throwNotNull(picture, ErrorCode.NOT_FOUND_ERROR);

        // 判断是否具有权限，公共图库只有管理员或自己创建的图片才能删除，空间图库只有本人才能删除
        checkPictureAuth(loginUser, picture);

        Long spaceId = picture.getSpaceId();
        // 开启事务
        transactionTemplate.execute(s -> {
            // 执行删除
            Boolean result = this.removeById(picture);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

            // 释放空间额度
            if (spaceId != null){
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, spaceId)
                        .setSql("totalSize = totalSize - " + picture.getPicSize())
                        .setSql("totalCount = totalCount - 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return picture;
        });

        // 清理文件
        clearPictureFile(picture);
    }

    @Override
    public void editPicture(PictureEditRequest editRequest, User loginUser) {
        ThrowUtils.throwIf(editRequest.getId() <= 0, ErrorCode.PARAMS_ERROR);
        // 在此处将实体类和 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(editRequest, picture);
        // 注意将 list 转为 string
        picture.setTags(JSONUtil.toJsonStr(editRequest.getTags()));
        // 设置编辑时间
        picture.setEditTime(new Date());
        // 数据校验
        this.validPicture(picture);
        // 判断是否存在
        long id = editRequest.getId();
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验权限
        checkPictureAuth(loginUser, oldPicture);
        picture.setSpaceId(oldPicture.getSpaceId());
        // 补充审核参数
        this.fillReviewParams(picture, loginUser);
        // 操作数据库
        boolean result = this.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }


    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest byBatchRequest, User loginUser) {
        // 搜索关键词
        String searchText = byBatchRequest.getSearchText();
        ThrowUtils.throwIf(StrUtil.isBlank(searchText), ErrorCode.PARAMS_ERROR, "搜索关键词不能为空");
        // 抓取数量
        Integer count = byBatchRequest.getCount();
        ThrowUtils.throwIf(count > 30, ErrorCode.PARAMS_ERROR, "最多30条");
        String namePrefix = byBatchRequest.getNamePrefix();
        if (StrUtil.isBlank(namePrefix)) {
            namePrefix = searchText;
        }
        // 根据搜索关键词，拼接抓取地址
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);
        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (Exception e) {
            log.info("获取图片失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取页面失败");
        }
        // 获取页面元素
        Element element = document.getElementsByClass("dgControl").first();
        if (ObjUtil.isNull(element)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取元素失败");
        }
        // 获取图片列表
        Elements imgElementList = element.select("img.mimg");
        int uploadCount = 0;
        for (Element imgElement : imgElementList) {
            String fileUrl = imgElement.attr("src");
            if (StrUtil.isBlank(fileUrl)) {
                log.info("当前链接为空，已跳过: {}", fileUrl);
                continue;
            }
            // 处理图片上传地址，防止出现转义问题
            int questionMarkIndex = fileUrl.indexOf("?");
            if (questionMarkIndex > -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
            }
            // 上传图片
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            // 设置图片名称
            pictureUploadRequest.setPicName(namePrefix + (uploadCount + 1));
            try {
                PictureVO pictureVO = this.uploadPicture(pictureUploadRequest, fileUrl, loginUser);
                log.info("图片上传成功, id = {}", pictureVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.error("图片上传失败", e);
                continue;
            }
            if (uploadCount >= count) {
                break;
            }
        }
        return uploadCount;
    }

    /**
     * 封装存储的图片实体对象
     *
     * @param loginUser
     * @param uploadPictureResult
     * @param pictureId
     * @return
     */
    private Picture buildPicture(User loginUser, UploadPictureResult uploadPictureResult, Long pictureId) {
        Picture picture = new Picture();

        picture.setUrl(uploadPictureResult.getUrl()); // 压缩地址（前端展示）
        picture.setOriginalUrl(uploadPictureResult.getOriginalUrl()); // 原图地址
        picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl()); // 缩略图地址
        picture.setName(uploadPictureResult.getPicName());
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setUserId(loginUser.getId());
        // 如果pictureId不为空，表示更新数据
        if (pictureId != null) {
            // 更新补充编辑时间，ID
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }
        // 填充审核信息
        fillReviewParams(picture, loginUser);
        return picture;
    }

    @Override
    public void fillReviewParams(Picture picture, User loginUser) {
        if (userService.isAdmin(loginUser) || picture.getSpaceId() != null) {
            // 管理员自动过审
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewerId(loginUser.getId());
            picture.setReviewMessage("管理员自动过审");
            picture.setReviewTime(new Date());
        } else {
            // 非管理员，创建或编辑都要改为待审核
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }
    }

    @Override
    public QueryWrapper<Picture> queryWrapper(PictureQueryRequest queryRequest) {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (queryRequest == null)
            return queryWrapper;
        Long id = queryRequest.getId();
        String name = queryRequest.getName();
        String introduction = queryRequest.getIntroduction();
        String category = queryRequest.getCategory();
        List<String> tags = queryRequest.getTags();
        Long picSize = queryRequest.getPicSize();
        Integer picWidth = queryRequest.getPicWidth();
        Integer picHeight = queryRequest.getPicHeight();
        Double picScale = queryRequest.getPicScale();
        String picFormat = queryRequest.getPicFormat();
        String searchText = queryRequest.getSearchText();
        Long userId = queryRequest.getUserId();
        String sortField = queryRequest.getSortField();
        String sortOrder = queryRequest.getSortOrder();
        Boolean isAsc = "ascend".equals(sortOrder) || queryRequest.getIsAsc();
        Integer reviewStatus = queryRequest.getReviewStatus();
        String reviewMessage = queryRequest.getReviewMessage();
        Long reviewerId = queryRequest.getReviewerId();
        Long spaceId = queryRequest.getSpaceId();
        Boolean nullSpaceId = queryRequest.getNullSpaceId();
        Date startEditTime = queryRequest.getStartEditTime();
        Date endEditTime = queryRequest.getEndEditTime();

        // 时间范围查询 <  >=
        if (!ObjUtil.hasNull(startEditTime, endEditTime) && DateUtil.between(startEditTime, endEditTime, DateUnit.MINUTE) > 0){
            // 开始时间小于等于当前时间
            queryWrapper.ge("editTime", startEditTime);
            // 结束时间小于等于当前时间
            queryWrapper.lt("editTime", endEditTime);
        }

        // 构造查询条件
        if (StrUtil.isNotBlank(searchText)) {
            // 拼接查询条件
            queryWrapper.and(w -> w.like("name", searchText)
                    .or()
                    .like("introduction", searchText));
        }
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        queryWrapper.isNull(nullSpaceId && ObjUtil.isEmpty(spaceId), "spaceId");

        // Json数组查询
        if (ObjUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like(StrUtil.isNotBlank(tag),
                        "tags",
                        String.format("\"%s\"", tag));
            }
        }
        // 排序
        queryWrapper.orderBy(StrUtil.isNotBlank(sortField), isAsc, sortField);
        return queryWrapper;
    }

    @Override
    public PictureVO getPictureVOById(Long id, User loginUser) {
        ThrowUtils.throwIf(id == null || id <= 0, ErrorCode.PARAMS_ERROR);
        Picture picture = this.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);

        // 空间权限校验
        if (picture.getSpaceId() != null) {
            checkPictureAuth(loginUser, picture);
        }
        PictureVO pictureVO = PictureVO.objToVo(picture);
        // 查询关联用户信息
        Long userId = pictureVO.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }

    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage) {
        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }
        // 对象列表 => 封装对象列表
        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
        // 1. 关联查询用户信息
        Set<Long> userIdSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            pictureVO.setUser(userService.getUserVO(user));
        });
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }

    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {
        ThrowUtils.throwNotNull(pictureReviewRequest);
        // 判断图片是否存在
        Long id = pictureReviewRequest.getId();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        String reviewMessage = pictureReviewRequest.getReviewMessage();

        Picture picture = this.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 设置审核状态
        Picture newPicture = new Picture();
        newPicture.setId(id);
        newPicture.setReviewStatus(reviewStatus);
        newPicture.setReviewMessage(reviewMessage);
        newPicture.setReviewTime(new Date());
        newPicture.setReviewerId(loginUser.getId());

        // 更新图片状态
        boolean b = this.updateById(newPicture);
        ThrowUtils.throwIf(!b, ErrorCode.OPERATION_ERROR);
    }


    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwNotNull(picture);
        // 从对象中取值
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }

    @Override
    public void checkPictureAuth(User loginUser, Picture picture) {
        Long spaceId = picture.getSpaceId();
        if (spaceId == null) {
            // 公共图库，仅本人或管理员可操作
            if (!picture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        } else {
            // 私有空间，仅空间管理员可操作
            if (!picture.getUserId().equals(loginUser.getId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
    }


    /**
     * 清理COS中的对象
     *
     * @param picture
     */
    @Async // 异步执行
    @Override
    public void clearPictureFile(Picture picture) {
        // 关联删除对象存储中的数据 TODO 判断该url地址是否被其他数据引用 (批量删除)
        String url = picture.getUrl();
        String thumbnailUrl = picture.getThumbnailUrl();
        String originalUrl = picture.getOriginalUrl();

/*        // 判断该url地址是否被其他数据引用
        boolean b = this.lambdaQuery()
                .eq(Picture::getUrl, url)
                .exists();
        if (b){
            url = ""; // 不删除
        }*/
        cosManager.deleteObject(url, originalUrl, thumbnailUrl);
    }
}




